package com.xwdeshj.servcie.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.servcie.MailServcie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * Created by BKWJA on 2019/3/19.
 * 邮件发送协议
 */
@Service("mailservcie")
public class MailServcieImpl implements MailServcie {

    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private JavaMailSender sender;

    @Value("${spring.mail.username}")
    private String from;

    @Value("${spring.mail.password}")
    private String psw;

    @Value("${spring.mail.host}")
    private String host;

    @Autowired
    private JavaMailSender mailSender;

    //logger日志
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public JSON sendEmil(String to, String subject, String message) {
        JSONObject result = new JSONObject();

        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

            //设置邮件会话参数
            Properties props = new Properties();
            //邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            //邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.auth", "true");
            final String username = from;
            final String password = psw;
            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            //通过会话,得到一个邮件,用于发送
            Message msg = new MimeMessage(session);
            //设置发件人
            msg.setFrom(new InternetAddress(from));
            //设置收件人,to为收件人,cc为抄送,bcc为密送
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
            msg.setSubject(subject);
            //设置邮件消息
            msg.setText(message);
            //设置发送的日期
            msg.setSentDate(new Date());

            //调用Transport的send方法去发送邮件
            Transport.send(msg);

            logger.info("----------------------邮件发送成功:"+dateFormat.format(new Date()));
            result.put("status", 0);
            result.put("msg", "ok");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("----------------------邮件发送失败：",dateFormat.format(new Date()),e);
            result.put("status", 40002);
            result.put("msg", e);
        }

        return result;
    }



    @Override
    public JSON sendHTMLEmil(String to, String subject, String message) {
        JSONObject result = new JSONObject();

        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

            //设置邮件会话参数
            Properties props = new Properties();
            //邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            //邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.auth", "true");
            final String username = from;
            final String password = psw;
            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

            helper.setTo(to);
            helper.setSubject(subject);
            //true：支持HTML发送邮件
            helper.setText(message,true);
            helper.setFrom(from);
            mailSender.send(mimeMessage);


            logger.info("----------------------邮件发送成功:"+dateFormat.format(new Date()));
            result.put("status", 0);
            result.put("msg", "ok");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("----------------------邮件发送失败：",dateFormat.format(new Date()),e);
            result.put("status", 40002);
            result.put("msg", e);
        }

        return result;
    }


    /**
     * 进行base64加密，防止中文乱码
     */
    public String changeEncode(String str) {

        try {
            str = MimeUtility.encodeText(new String(str.getBytes(), "UTF-8"),
                    "UTF-8", "B"); // "B"代表Base64

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return str;
    }



}
